<!--
 * @Descripttion: 文件说明
 * @version: V1.0
 * @Author: GW
 * @Date: 2022-05-09 14:16:14
 * @LastEditors: GW
 * @LastEditTime: 2022-06-14 17:05:53
-->
<!-- 新增凭证模板弹窗 -->
<template>
    <a-modal class="filed-table" v-model="templateModal" title="新增凭证模板" @cancel="cancel" width="1000px">
        <div class="finance-template-box-header">
            <div class="filter">
                <div class="filter-label">模板编号:</div>
                <div class="filter-control">
                    <a-input @input="code=code.replace(/[^\d]/g,'')" placeholder="请填写模板编号" v-model.trim="code"></a-input>
                </div>
            </div>
            <div class="filter">
                <div class="filter-label">模板名称:</div>
                <div class="filter-control">
                    <a-input v-model.trim="name" placeholder="请填写模板名称"></a-input>
                </div>
            </div>
            <div class="filter" style="width:120px">
                <div class="filter-label"><span style="color:red">* </span>凭证字:</div>
                <div class="filter-control">
                    <div class="clearfix">
                        <a-input read-only class="text-center" style="width:90%;float:left" @click="searchGroup('credentialsSearch')" v-model="dataJson.classWord" autocomplete="off">
                        </a-input>
                    </div>
                    <search-group-header ref="credentialsSearch" :inputValue="dataJson.classWord" :componentName="'category'" @clickItem="searchBackData"></search-group-header>
                </div>
            </div>
            <div class="filter" style="width:220px">
                <div class="filter-label">凭证分类:</div>
                <div class="filter-control">
                    <a-select @change="typeChange" v-model="credentialsType" style="width:150px;" placeholder="请选择凭证分类">
                        <a-select-option :label="item.title" v-for="(item, index) in typeData" :key="item.id + index" :value="item.id">
                            {{item.name}}
                        </a-select-option>
                    </a-select>
                </div>
            </div>
            <div class="filter">
                <div class="filter-label">描述:</div>
                <div class="filter-control">
                    <a-input v-model.trim="remarks"></a-input>
                </div>
            </div>
        </div>

        <a-table id="credentials_tb" class="atable-edit" style="min-height:200px;" :columns="columnsModal" :customRow="customClick" :data-source="dataSourceModal" :pagination="false" bordered>
            <template v-for="item in editColumn" :slot="item" slot-scope="text, record ,index">
                <div>
                    <editable-cell v-if="isRouterAlive" :record="record" :col="item" :text="text" @showEditFormula="showEditFormula(record,index)" @showModalAuxiliary="showModalAuxiliary" @change="onCellChange(index, item, $event)" />
                </div>
            </template>
        </a-table>
        <template slot="footer">
            <a-button type="primary" @click="templateSave">保存</a-button>
            <a-button @click="cancel" class="margin-left-10">关闭</a-button>
        </template>
        <auxiliary ref="auxiliaryRef" :dataSource="dataSourceModal" :currentIndexTable="currentIndexTable" @auxiliaryBack="auxiliaryBack"></auxiliary>
    </a-modal>
</template>
<script>
import { save, detail } from "@/api/finance/endCredentials";
import editableCell from "@/views/finance/accounting/editTable/EditableCell";
import auxiliary from "@/components/Finance/credentials/auxiliary/auxiliary";
import searchGroupHeader from "@/components/PopUpLayer/searchGroupHeader";

import { listType } from "@/api/finance/endCredentials";

export default {
    components: {
        editableCell,
        auxiliary,
        searchGroupHeader
    },
    props: {
        nowId: {
            type: Number,
            default: null
        },
        vtype: {//凭证分类//1常用凭证2规则凭证
            type: Number,
            default: 1
        },
        typeId: {//凭证类别id
            type: Number,
            default: null
        }
    },
    data () {
        return {
            columnsModal: [{
                title: <div><span style="color:red">*</span>摘要</div>,
                dataIndex: "remark",
                width: 100,
                align: 'left',
                scopedSlots: { customRender: 'remark' },
            }, {
                title: <div><span style="color:red">*</span>科目名称</div>,
                dataIndex: "accountingName",
                width: 80,
                align: 'left',
                scopedSlots: { customRender: 'accountingName' },
            }, {
                title: '辅助项',
                dataIndex: 'auxiliaryItem',
                width: 180,
                scopedSlots: { customRender: 'auxiliaryItem' },
                ellipsis: true,
            }, {
                title: <div><span style="color:red">*</span>方向</div>,
                dataIndex: "amountDirection",
                width: 50,
                align: 'left',
                scopedSlots: { customRender: 'amountDirection' },
            }, {
                title: "金额",
                dataIndex: "amountBtn",
                width: 80,
                align: 'left',
                scopedSlots: { customRender: 'amountBtn' },
            }],
            templateModal: false,
            code: null,//模板编号
            name: null,//模板名称
            remarks: null,
            isRouterAlive: true,
            dataSourceModal: [],
            editColumn: [],
            credentialsType: null,//凭证分类
            currentIndexTable: null,
            customClick: (record, index) => ({
                on: {
                    // contextmenu: (e) => {//右键事件
                    //     e.preventDefault();
                    //     this.openMenu(e);
                    //     console.log('右键点击的', index);
                    //     this.thisClickId = index;
                    // },
                    click: () => {
                        this.currentIndexTable = index;
                    }
                },
            }),
            dataJson: {
                classWord: null,
                vclassId: null,
                vclassName: null,
            },
            typeData: [],
        }
    },
    mounted () {
        this.editColumnArray();

    },
    methods: {
        typeChange (e, v) {
            console.log(e, v)
            this.credentialsType = e;
        },
        getTypeList () {
            listType({ type: this.vtype }).then(res => {
                if (res.code === 200) {
                    this.typeData = res.data;

                    if (this.typeId) {
                        console.log(this.typeId)
                        this.credentialsType = this.typeId;
                    }
                }
            })
        },
        templateEdit (data, type) {
            this.getTypeList();
            //新增 || 修改 模板
            if (data == 1) {
                //新增
                this.templateModal = true;
                this.nowId = null;
                this.code = null;
                this.name = null;
                this.vtype = type;
                this.credentialsType = null;

                this.remarks = null;
                this.dataSourceModal = [];
                this.complementTable();//补齐表格
            } else {
                //修改
                this.templateModal = true;
                let backData = _.clone(data);
                this.nowId = backData.id;
                this.code = backData.code;
                this.name = backData.name;
                this.remarks = backData.remarks;
                this.vtype = backData.vtype;
                this.credentialsType = backData.type;
                this.dataJson.classWord = backData.classWord;
                this.dataJson.vclassId = backData.vclassId;
                this.dataJson.vclassName = backData.vclassName;

                //获取详情
                this.getDetails(backData.id);
            }
        },
        cancel () {
            this.templateModal = false;
        },
        reload () {
            //强制刷新表格
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        searchGroup (type) {
            if (type == 'credentialsSearch') {
                this.$refs.credentialsSearch.showModal();
            } else if (type == 'employees') {
                this.$refs.reviewerRef.showModal();
            }
        },
        searchBackData (record) {
            if (record) {
                this.$set(this.dataJson, 'classWord', record.classWord);
                this.$set(this.dataJson, 'vclassId', record.id);
                this.$set(this.dataJson, 'vclassName', record.className);
            }
        },
        onCellChange (indexTable, dataIndex, value) {
            const dataSourceModal = [...this.dataSourceModal];
            const target = dataSourceModal.find((item, index) => index === indexTable);
            console.log(target, dataIndex, value);

            if (dataIndex == 'accountingName') {
                //限制科目
                if (value) {
                    console.log(value.constructor == Object)
                    console.log(value.constructor == Array)
                    if (value.constructor == Object) {
                        target['accountingId'] = value.id;
                        target['accountingName'] = value.treeNames.split('/').join('_');;
                        target['accountingCode'] = value.code;
                    } else if (value.constructor == Array) {
                        target['accountingName'] = value.map(o => o.name).join(',');
                        target['accountingId'] = value.map(o => o.id).join(',');
                    }
                } else {
                    target['accountingName'] = null;
                    target['accountingId'] = null;
                    target['accountingCode'] = null;
                }

            } else {
                if (target) {
                    // target[dataIndex] = value;
                    this.$set(target, dataIndex, value)
                }
            }
            this.$nextTick(() => {
                this.dataSourceModal = dataSourceModal;
                console.log(this.dataSourceModal)
                this.reload();
            })

        },
        showModalAuxiliary (id) {
            console.log('进入了---------修改的弹窗');
            //根据科目id获取科目详情
            this.$refs.auxiliaryRef.show(id);
        },
        auxiliaryBack (data) {
            this.dataSourceModal = data;
            this.reload();
        },
        getDetails (id) {
            detail({ id: id, vtype: this.vtype }).then(res => {
                if (res.code === 200) {
                    this.dataSourceModal = res.data.orderDetailList;
                    this.complementTable();//补齐表格
                }
            })
        },
        //获取可编辑的列名
        editColumnArray () {
            let editcloumn = [];
            this.columnsModal.forEach((item, index) => {
                editcloumn.push(item.dataIndex);
            });
            this.editColumn = editcloumn;
        },
        //补齐表格
        complementTable () {
            let length = this.dataSourceModal.length;
            if (this.dataSourceModal.length < 10) {
                let forlength = 10 - length;
                for (let i = 0; i < forlength; i++) {
                    let array = {};
                    this.dataSourceModal.push(array);
                }
            }
            this.$nextTick(() => {
                this.reload();
            })
        },
        templateSave () {
            let requestData = {
                code: this.code,
                name: this.name,
                remarks: this.remarks,
                classWord: this.dataJson.classWord,
                vclassId: this.dataJson.vclassId,
                vclassName: this.dataJson.vclassName,
                vtype: this.vtype,//1:常用凭证 2：规则凭证
                type: this.credentialsType,//凭证分类
                id: this.nowId,
                orderDetailList: this.dataSourceModal.filter(res => res.accountingId != null),
            }

            let d = requestData.orderDetailList
            for (let index = 0; index < d.length; index++) {
                if (d[index].remark == null) {
                    this.$message.warning('第' + Number(index + 1) + '行，摘要必须填写')
                    return
                } else if (d[index].amountDirection == null) {
                    this.$message.warning('第' + Number(index + 1) + '行，方向必须选择')
                    return
                }
            }
            if (requestData.orderDetailList.length < 1) {
                this.$message.warning('请填写凭证模板明细');
                return;
            }
            save(requestData).then(res => {
                if (res.code === 200) {
                    this.$message.success('保存成功');
                    this.templateModal = false;
                    this.$emit('getDataList');
                }
            })
        },
        showEditFormula (record, index) {
            //显示编辑公式弹窗
            this.$emit('showEditFormula', { record, index })
        },
        //公式回显 置值
        formulaBack (backdata) {
            this.dataSourceModal.forEach((item, index) => {
                if (backdata.index == index) {
                    item.formulaList = backdata.data;
                }
            })
        }
    }
}
</script>
<style lang="less" scoped>
</style>